﻿using Castle.Core.Logging;
using com.ytocargo.Core.AirPortCharts;
using com.ytocargo.Core.AirPortInfos;
using com.ytocargo.Core.Charts;
using com.ytocargo.Core.GeneralDocs;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yto.Common;
using Yto.Common.Dependency;
using Yto.Threading;
using Yto.Threading.BackgroundWorkers;
using Yto.Unitwork;

namespace com.ytocargo.Application.ChartsJobs
{
    public class ChartsJobManager : TimedBgdWorker, IChartsJobManager, ISingleton
    {
        private readonly ICtnManager _ctnManager;
        private IAirPortInfoStore airPortInfoStore;
        private IAirPortChartStore airPortChartStore;
        private IChartStore chartStore;
        private IGeneralDocStore generalDocStore;
        private ILogger _logger;
        private IUnitManager unitManager;

        public ChartsJobManager(BaseTimer baseTimer,
            ICtnManager ctnManager,
            IAirPortInfoStore airPortInfo,
            IAirPortChartStore airPortChart,
            IChartStore chart,
            IGeneralDocStore generalDoc)
            :base(baseTimer)
        {
            JobPeriod = int.TryParse(ConfigurationManager.AppSettings["Period"], out int tempValue)
                        ? tempValue : 5000;
            baseTimer.Period = JobPeriod;
            _ctnManager = ctnManager;
            airPortInfoStore = airPortInfo;
            airPortChartStore = airPortChart;
            chartStore = chart;
            generalDocStore = generalDoc;

            _logger = _ctnManager.IsRegisted<ILoggerFactory>() ?
                _ctnManager.Resolver<ILoggerFactory>().Create(typeof(ChartsJobManager))
                : NullLogger.Instance;
            unitManager = ctnManager.Resolver<IUnitManager>();
        }

        public int JobPeriod { get; private set; }

        protected override void DoWork()
        {
            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            using (var uw = unitManager.Begin())
            {
                var airPortInfos = airPortInfoStore.GetAll();
                var airPortCharts = airPortChartStore.GetAll();

                var notHaveChartPorts = airPortInfos.Where(p => !airPortCharts.Any(c => c.Id == p.Id));

                //var charts = chartStore.GetAll().Where(x => notHaveChartPorts.Any(p => p.Id == x.AirportIcao));

                var listNotHaveChartsPorts = notHaveChartPorts.ToList();
                //var listCharts = charts.ToList();

                foreach (var item in listNotHaveChartsPorts)
                {
                    var listCharts = chartStore.GetAll().Where(x => x.AirportIcao == item.Id).OrderBy(x => x.PAGE_NUMBER).ToList();
                    if (listCharts.Count > 0)
                    {
                        var airPortChart = airPortChartStore.GetByIdAsync(item.Id).Result;
                        if (airPortChart == null)
                        {
                            airPortChart = new AirPortChart();
                        }
                        var UnUpdateDir = ConfigurationManager.AppSettings["UnUpdateDir"];
                        var CsvPath = ConfigurationManager.AppSettings["CsvPathCurrent"];
                        if (!FileHelper.DirectoryExist(UnUpdateDir))
                        {
                            FileHelper.CreateDirectory(UnUpdateDir);
                        }
                        foreach (var chart in listCharts)
                        {
                            var filePath = chart.FilePath.Substring(0, chart.FilePath.LastIndexOf('/') + 1);
                            if (chart.PAGE_NUMBER == null)
                            {
                                var fileName = chart.AirportName.Replace("/", "") + ".pdf";
                                if (FileHelper.FileExist(CsvPath + filePath + fileName))
                                {
                                    FileHelper.CopyFile(CsvPath + filePath + fileName, UnUpdateDir + fileName);
                                }
                                airPortChart.XZPICTFILE1 = fileName;
                                airPortChart.AIRPORTNAME = chart.AirportName;
                            }
                            else
                            {
                                switch (chart.PAGE_NUMBER.Substring(0, 1))
                                {
                                    case "1":
                                        var fileName = chart.AirportIcao + "-" + chart.PAGE_NUMBER.Replace("/", "") + ".pdf";
                                        if (FileHelper.FileExist(CsvPath + filePath + fileName))
                                        {
                                            FileHelper.CopyFile(CsvPath + filePath + fileName, UnUpdateDir + fileName);
                                        }

                                        if (!string.IsNullOrWhiteSpace(airPortChart.ZLPICTFILE))
                                        {
                                            airPortChart.ZLPICTFILE += "/" + fileName;
                                        }
                                        else
                                            airPortChart.ZLPICTFILE = fileName;
                                        break;
                                    case "2":
                                        fileName = chart.AirportIcao + "-" + chart.PAGE_NUMBER.Replace("/", "") + ".pdf";
                                        if (FileHelper.FileExist(CsvPath + filePath + fileName))
                                        {
                                            FileHelper.CopyFile(CsvPath + filePath + fileName, UnUpdateDir + fileName);
                                        }

                                        if (!string.IsNullOrWhiteSpace(airPortChart.APPICTFILE))
                                        {
                                            airPortChart.APPICTFILE += "/" + fileName;
                                        }
                                        else
                                            airPortChart.APPICTFILE = fileName;
                                        break;
                                    case "3":
                                        fileName = chart.AirportIcao + "-" + chart.PAGE_NUMBER.Replace("/", "") + ".pdf";
                                        if (FileHelper.FileExist(CsvPath + filePath + fileName))
                                        {
                                            FileHelper.CopyFile(CsvPath + filePath + fileName, UnUpdateDir + fileName);
                                        }

                                        if (!string.IsNullOrWhiteSpace(airPortChart.LCPICTFILE))
                                        {
                                            airPortChart.LCPICTFILE += "/" + fileName;
                                        }
                                        else
                                            airPortChart.LCPICTFILE = fileName;
                                        break;
                                    case "4":
                                        fileName = chart.AirportIcao + "-" + chart.PAGE_NUMBER.Replace("/", "") + ".pdf";
                                        if (FileHelper.FileExist(CsvPath + filePath + fileName))
                                        {
                                            FileHelper.CopyFile(CsvPath + filePath + fileName, UnUpdateDir + fileName);
                                        }

                                        if (!string.IsNullOrWhiteSpace(airPortChart.JCPICTFILE))
                                        {
                                            airPortChart.JCPICTFILE += "/" + fileName;
                                        }
                                        else
                                            airPortChart.JCPICTFILE = fileName;
                                        break;
                                    case "5":
                                        fileName = chart.AirportIcao + "-" + chart.PAGE_NUMBER.Replace("/", "") + ".pdf";
                                        if (FileHelper.FileExist(CsvPath + filePath + fileName))
                                        {
                                            FileHelper.CopyFile(CsvPath + filePath + fileName, UnUpdateDir + fileName);
                                        }

                                        if (!string.IsNullOrWhiteSpace(airPortChart.JJPICTFILEILS))
                                        {
                                            airPortChart.JJPICTFILEILS += "/" + fileName;
                                        }
                                        else
                                            airPortChart.JJPICTFILEILS = fileName;
                                        break;
                                    case "6":
                                        fileName = chart.AirportIcao + "-" + chart.PAGE_NUMBER.Replace("/", "") + ".pdf";
                                        if (FileHelper.FileExist(CsvPath + filePath + fileName))
                                        {
                                            FileHelper.CopyFile(CsvPath + filePath + fileName, UnUpdateDir + fileName);
                                        }

                                        if (!string.IsNullOrWhiteSpace(airPortChart.JJPICTFILEVOR))
                                        {
                                            airPortChart.JJPICTFILEVOR += "/" + fileName;
                                        }
                                        else
                                            airPortChart.JJPICTFILEVOR = fileName;
                                        break;
                                    case "7":
                                        fileName = chart.AirportIcao + "-" + chart.PAGE_NUMBER.Replace("/", "") + ".pdf";
                                        if (FileHelper.FileExist(CsvPath + filePath + fileName))
                                        {
                                            FileHelper.CopyFile(CsvPath + filePath + fileName, UnUpdateDir + fileName);
                                        }

                                        if (!string.IsNullOrWhiteSpace(airPortChart.JJPICTFILENDB))
                                        {
                                            airPortChart.JJPICTFILENDB += "/" + fileName;
                                        }
                                        else
                                            airPortChart.JJPICTFILENDB = fileName;
                                        break;
                                    case "8":
                                        fileName = chart.AirportIcao + "-" + chart.PAGE_NUMBER.Replace("/", "") + ".pdf";
                                        if (FileHelper.FileExist(CsvPath + filePath + fileName))
                                        {
                                            FileHelper.CopyFile(CsvPath + filePath + fileName, UnUpdateDir + fileName);
                                        }

                                        if (!string.IsNullOrWhiteSpace(airPortChart.JJPICTFILEMS))
                                        {
                                            airPortChart.JJPICTFILEMS += "/" + fileName;
                                        }
                                        else
                                            airPortChart.JJPICTFILEMS = fileName;
                                        break;
                                    default:
                                        fileName = chart.AirportIcao + "-" + chart.PAGE_NUMBER.Replace("/", "") + ".pdf";
                                        if (FileHelper.FileExist(CsvPath + filePath + fileName))
                                        {
                                            FileHelper.CopyFile(CsvPath + filePath + fileName, UnUpdateDir + fileName);
                                        }

                                        if (!string.IsNullOrWhiteSpace(airPortChart.XZPICTFILE2))
                                        {
                                            airPortChart.XZPICTFILE2 += "/" + fileName;
                                        }
                                        else
                                            airPortChart.XZPICTFILE2 = fileName;
                                        break;
                                }

                            }
                        }

                        if (airPortChart.Id == null)
                        {
                            airPortChart.Id = item.Id;
                            airPortChartStore.InsertAsync(airPortChart);
                        }
                        else
                        {
                            airPortChartStore.UpdateAsync(airPortChart);
                        }

                        _logger.Info($"airPort {airPortChart.Id} is updated at {DateTime.Now}");
                    }
                }
                uw.Complete();
            }
            //sw.Stop();
            //_logger.Info($"添加AirPortChart用时： { sw.ElapsedMilliseconds }");
        }
    }
}
